import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';
import { Repository } from 'typeorm';
import { hashSync } from 'bcrypt';
import { GLOBAL_CONSTANTS } from 'src/global/constants';

@Injectable()
export class UsersService {
  findByPhone(phone: string) {
    return this.userRepository.findOneBy({ phone });
  }
  findByEmail(email: string) {
    return this.userRepository.findOneBy({ email });
  }
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  create(createUserDto: CreateUserDto) {
    /** 密码加密 + 盐 */
    const hashedPassword = hashSync(
      createUserDto.password,
      GLOBAL_CONSTANTS.salt,
    );
    createUserDto.password = hashedPassword;
    return this.userRepository.save(createUserDto);
  }

  findAll() {
    return this.userRepository.find();
  }

  findOne(userId: string) {
    return this.userRepository.findOneBy({ userId });
  }

  findByUsername(username: string) {
    return this.userRepository.findOneBy({ username });
  }

  update(updateUserDto: UpdateUserDto) {
    if (!updateUserDto.userId) {
      throw new NotFoundException();
    }
    return this.userRepository.update(updateUserDto.userId, updateUserDto);
  }

  remove(userId: string) {
    return this.userRepository.delete(userId);
  }

  updatePassword(userId: string, password: string) {
    /** 密码加密 + 盐 */
    const hashedPassword = hashSync(password, GLOBAL_CONSTANTS.salt);
    return this.userRepository.update(userId, { password: hashedPassword });
  }
}
